package com.aifeng.hassan_food.mine

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import com.aifeng.base.BaseActivity
import com.aifeng.base.addItems
import com.aifeng.base.loadRoundedImage
import com.aifeng.base.setHtmlSmall
import com.aifeng.common_ui.base.oneClick
import com.aifeng.common_ui.helper.*
import com.aifeng.common_ui.view.FullyLinearLayoutManager
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.WebActivity
import com.aifeng.model.BaseUrl
import com.aifeng.model.CommonData
import com.aifeng.model.OrderData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.DialogHelper.showHintDialog
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.getExtra
import com.aifeng.utils.subscribeByFinally
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.OrderViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.activity_order_refund_detail.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.koin.androidx.viewmodel.ext.android.getViewModel

class OrderRefundDetailActivity : BaseActivity() {

    private var mData: OrderData? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order_refund_detail)
        initTitle(title = "退款详情")

        getData()
    }

    override fun getViewModel() = getViewModel<OrderViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        refund_list.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(baseContext)
            mAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_shop_inner_list_80) { inner, jector ->

                    val index = mList.indexOf(inner)
                    val isLast = index == mList.size - 1

                    jector.text(R.id.item_shop_name, inner.goodsname)
                        .text(R.id.item_shop_type, "规格：${inner.specs}")
                        .text(
                            R.id.item_shop_price,
                            setHtmlSmall("¥ ${inner.price.formatDecimalWhenHave()}", "¥")
                        )
                        .text(R.id.item_shop_num, "x${inner.num}")
                        .with<ImageView>(R.id.item_shop_img) { view ->
                            val imgs = inner.goodimg.split(",")
                            view.loadRoundedImage(url = imgs[0].scaleImage())
                        }
                        .visibility(
                            R.id.item_shop_set,
                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_shop_divider,
                            if (isLast) View.GONE else View.VISIBLE
                        )
                }
                .attachTo(this)
        }

        refund_service.oneClick { startActivity<WebActivity>("title" to "在线客服") }
        refund_del.oneClick { mData?.let { deleteOrder(it.id) } }
    }

    private fun deleteOrder(orderId: String) {
        showHintDialog(
            title = "删除订单",
            hint = "确定要删除订单吗？"
        ) {
            getViewModel().orderHandle(
                url = BaseUrl.delOrder,
                orderId = orderId,
                userId = getString("userId")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        LiveEventBus.get("refundList").post(intent.getExtra("index"))
                        ActivityStack.screenManager.popActivities(this::class.java)
                    }
                )
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().orderDetail(
            intent.getExtra("id"),
            getString("userId")
        )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.clear()
                    mList.addItems(it.goodlist)
                    mAdapter.updateData(mList)

                    refund_shop.text = it.shopname
                    mData = it.order
                    setData()
                }
            )
    }

    @SuppressLint("SetTextI18n")
    private fun setData() {
        mData?.let {
            refund_back.text = "¥ ${it.paytotal.formatDecimal()}"
            refund_time1.text = it.applydate.toNotLong().getTimeString()
            refund_order.text = "订单编号：${it.orderno}"
        }
    }

}
